#include "pch.h"
#include "Instance.h"

namespace mini
{

	CInstance::CInstance()
	{

	}

	CInstance::~CInstance()
	{
		SafeRelease(mpInstanceBuffer);
	}

	void CInstance::setInstanceData(void* pData, int nSize, int nCount)
	{
		assert(nCount > 0);
		assert(nSize == sizeof(Instance_P) || nSize == sizeof(Instance_PC));

		SafeRelease(mpInstanceBuffer);
		mInstanceTypeSize = nSize;
		mInstanceCount = nCount;
		D3D11_BUFFER_DESC instanceBufferDesc;
		D3D11_SUBRESOURCE_DATA instanceData;

		// Set up the description of the instance buffer.
		instanceBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
		instanceBufferDesc.ByteWidth = nSize * nCount;
		instanceBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
		instanceBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
		instanceBufferDesc.MiscFlags = 0;
		instanceBufferDesc.StructureByteStride = 0;

		// Give the subresource structure a pointer to the instance data.
		instanceData.pSysMem = pData;
		instanceData.SysMemPitch = 0;
		instanceData.SysMemSlicePitch = 0;

		// Create the instance buffer.
		HRESULT hr = GEngine->getDevice()->getDevice()->CreateBuffer(&instanceBufferDesc, &instanceData, &mpInstanceBuffer);
		assert(hr == S_OK);
		//D3D11_MAPPED_SUBRESOURCE mappedResource;
		//// Lock the tessellation constant buffer so it can be written to.
		//hr = GEngine->getDevice()->getDeviceContext()->Map(mpInstanceBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);

		//GEngine->getDevice()->getDeviceContext()->Unmap(mpInstanceBuffer, 0);
		//
		auto units = getMeshUnits();
		for (auto item : units)
		{
			item->setInstance(mpInstanceBuffer, nSize, nCount);
		}
		updateBoundBox();
	}

	void CInstance::updateInstanceData(void* pData, int nSize, int nCount)
	{

	}

	void CInstance::updateBoundBox()
	{

	}

}